package com.caigou.modules.data.ui.comment

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentItemBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.databinding.ActivityCommentDetailBinding
import com.caigou.modules.data.R
import com.caigou.modules.data.adpter.CommentDetailItemAdapter
import com.caigou.modules.data.viewmodel.CommentViewModel
import com.caigou.modules.data.viewmodel.LikeViewModel
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.NgvChildImageView
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/19
 */
@Route(path = RouterPath.Data.PAGE_COMMENT_DETAIL)
@AndroidEntryPoint
class CommentDetailActivity : BaseActivity() {
    private lateinit var binding: ActivityCommentDetailBinding

    private val commentViewModel: CommentViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    @Autowired(name = AppConstants.COMMENT_ITEM_BEAN)
    lateinit var commentItemBean: CommentItemBean

    @JvmField
    @Autowired(name = AppConstants.DATA_TYPE)
    var dataType = 3

    private val mAdapter: DefaultNgvAdapter<String> by lazy {
        DefaultNgvAdapter(100, GlideDisplay())
    }

    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(this)
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(this)
    }

    private val itemAdapter: CommentDetailItemAdapter by lazy {
        CommentDetailItemAdapter(this, mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCommentDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.commentDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.commentDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchCommentDetail()
            }
        }

        binding.commentDetailBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance()
                    .build(RouterPath.Data.PAGE_COMMENT_REPLY)
                    .withObject(AppConstants.COMMENT_ITEM_BEAN, commentItemBean)
                    .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, commentItemBean)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        if (commentItemBean.replyChildren.isNullOrEmpty()) {
            binding.commentDetailLlEmpty.visibility = View.VISIBLE
            binding.commentDetailRecyclerView.visibility = View.GONE
        } else {
            binding.commentDetailLlEmpty.visibility = View.GONE
            binding.commentDetailRecyclerView.visibility = View.VISIBLE
        }

        binding.commentDetailIvAvatar.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                .withString(AppConstants.USER_ID, commentItemBean.replyUserInfoVo.userId)
                .navigation()
        }

        itemAdapter.setOnItemChildClickListener { _, view, position ->
            val item = itemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_detail_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
            }
        }

        handleCommentUI()

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentDetail()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(commentViewModel.commentDetailLiveData, ::handleGetCommentDetail)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
    }

    private fun handleGetCommentDetail(result: Resource<CommentItemBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论详情异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }
                commentItemBean = result.data!!
                handleCommentUI()
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.commentDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchCommentDetail()
                }
            }
        }
    }

    private fun handleCommentUI() {
        if (TextUtils.isEmpty(commentItemBean.replyUserInfoVo.headImg)) {
            binding.commentDetailIvAvatar.setImageResource(R.drawable.img_comm_avatar)
        } else {
            ImageLoader.loadCircle(this, commentItemBean.replyUserInfoVo.headImg, binding.commentDetailIvAvatar)
        }
        binding.commentDetailTvNickname.text = commentItemBean.replyUserInfoVo.nickName
        binding.commentDetailTvTime.text = commentItemBean.createTime
        binding.commentDetailTvContent.text = commentItemBean.content

        binding.commentDetailTvLike.text = commentItemBean.nicePoint.toString()
        if (commentItemBean.like) {
            binding.commentDetailIvLike.setImageResource(R.drawable.img_data_like)
            binding.commentDetailTvLike.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.commentDetailIvLike.setImageResource(R.drawable.img_data_unlike)
            binding.commentDetailTvLike.setTextColor(Color.parseColor("#505050"))
        }
        binding.commentDetailIvLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (commentItemBean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setCommentLike(
                        commentItemBean.replyId, dataType,
                        AppBackgroundInfo.instance.userBean!!.userId,
                        commentItemBean.replyUserInfoVo.userId
                    )
                }
            } else {
                showToast("请您先登录")
            }
        }

        if (commentItemBean.imgs.size > 0) {
            binding.commentDetailNgvDisplay.run {
                visibility = View.VISIBLE
                setSingleImageSize(TypedValue.COMPLEX_UNIT_DIP, 150, 200)
                mAdapter.dataList = commentItemBean.imgs
                mAdapter.setOnChildClickListener(object : DefaultNgvAdapter.OnChildClickedListener<String> {
                    override fun onPlusImageClicked(plusImageView: ImageView?, dValueToLimited: Int) {

                    }

                    override fun onContentImageClicked(position: Int, data: String?, childImageView: NgvChildImageView?) {
                        data?.apply {
                            showImgsPreview(this@CommentDetailActivity, commentItemBean.imgs, commentItemBean.imgs.indexOf(this))
                        }
                    }

                    override fun onImageDeleted(position: Int, data: String?) {
                    }
                })
                adapter = mAdapter
            }
        }

        binding.commentDetailRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = itemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        itemAdapter.setList(commentItemBean.replyChildren)
    }

    private fun fetchCommentDetail() {
        commentViewModel.getCommentDetail(commentItemBean.dataId, commentItemBean.replyId, commentItemBean.replyUserInfoVo.userId, dataType)
    }
}